import { ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { ComputerService } from 'app/modules/computer/services/computer.service';
import { PersonnelService } from 'app/modules/personnel/services/personnel.service';
import { weekdays } from 'moment';
import { ZoneService, Zone, ZoneDetail } from 'app/modules/zone/services/zone.service';
import _ from 'lodash';
import { Injector } from '@angular/core';
import { from } from 'rxjs';
import { MatDialog } from '@angular/material';
import { ZoneComputerAddComponent } from 'app/modules/zone-resources/zone-computer-add/zone-computer-add.component';

import { TaskPeriod, TaskService, TaskTarget, TaskType } from '../../services/task.service';
// import { SelectComputerComponent } from '../select-computer/select-computer.component';
import { SelectPersonnelComponent } from '../select-personnel/select-personnel.component';
import { SelectSoftwareComponent } from '../select-software/select-software.component';
import { SelectZoneComponent } from '../select-zone/select-zone.component';
import { Step3Component } from './step-3/step-3.component';
import { Step4Component } from './step-4/step-4.component';
import { FormBuilder } from '@angular/forms';
import { ToasterService } from 'app/modules/share/services/toaster.service';
import { Step2SelectPersonnelComponent } from './step2-select-personnel/step2-select-personnel.component';

@Component({
  selector: 'm-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.scss'],
})
export class AddComponent implements OnInit {
  public taskType = TaskType;
  public taskPeriod = TaskPeriod;
  public taskTarget = TaskTarget;
  steps = TaskAddSteps;
  readonly clientSteps = ClientAddSteps;
  readonly weekdayNames = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
  readonly taskTargetList = [
    TaskTarget.Zone,
    TaskTarget.Computer,
    TaskTarget.Personnel,
    TaskTarget.Software,
  ];

  // @ViewChild(SelectComputerComponent) private computerComponent: SelectComputerComponent;
  @ViewChild(Step2SelectPersonnelComponent) private computerComponent: Step2SelectPersonnelComponent;
  @ViewChild(SelectPersonnelComponent) private personnelComponent: SelectPersonnelComponent;
  @ViewChild(SelectSoftwareComponent) private softwareComponent: SelectSoftwareComponent;
  @ViewChild(SelectZoneComponent) private zoneComponent: SelectZoneComponent;
  @ViewChild(Step3Component) private step3Component: Step3Component;
  @ViewChild(Step4Component) private step4Component: Step4Component;
  constructor(
    // private _inject: Injector,
    // public dialog = _inject.get(MatDialog),
    private router: Router,
    private taskManager: TaskService,
   
    private personnelManager: PersonnelService,
    private computerManager: ComputerService,
    private ref: ChangeDetectorRef,
    private toaster: ToasterService,
  ) {}

  result$ = from([{}]);

  current = 0;
  child = 0;
  taskTypeModel = TaskType.SystemUpgrade;
  taskPeriodModel = TaskPeriod.Now;
  taskTargetModel = TaskTarget.Zone;
  weekdays = [false, false, false, false, false, false, false];
  taskTime = { hour: 3, minute: 0 };
  taskDateModel = { year: 2000, month: 1, day: 2 };
  scriptFileName = '';
  scriptFile: File;

  fb = new FormBuilder();
  scriptForm = this.fb.group({
    script: this.fb.group({
      name: [''],
      content: [''],
      upload_at: [''],
    }),
  });
  scriptDesc: any;//脚本说明

  ngOnInit() {
    let today = new Date();
    // var tomorrow = new Date();
    // tomorrow.setDate(today.getDate() + 1);
    this.taskDateModel.year = today.getFullYear();
    this.taskDateModel.month = today.getMonth() + 1;
    this.taskDateModel.day = today.getDate();
    this.taskTime.hour = today.getHours();
    this.taskTime.minute = today.getMinutes();
  }

  // async openModal(c: any) {
  //   const addDialog = this.dialog.open<{ zone: Zone }>(c, { width: '1120px' });
  //   const result = await addDialog.afterClosed().toPromise();
  //   if (result) {
  //     this.reload();
  //   }
  // }

  // reload() {
	// 	this.router.navigated = false;
	// 	this.router.navigate([], { queryParamsHandling: 'merge' });
  // }
  

  // addComputer() {
  //   this.openModal(ZoneComputerAddComponent);
  // }

  stepperChange(value: number) {
    this.taskTargetModel = this.taskTarget.Zone;
    // console.log(this.taskTargetModel);
    // console.log(this.scriptForm);
  }
  nextStep(){
    //第三步 点击下一步 需要做校验
    if(this.current == 2){
      if(!this.step3Component.architectureModel ||!this.step3Component.packageModel){
        this.toaster.warn('请选择任务执行内容');
        return ;
      }else{
        let task = {
          arch:this.step3Component.architectureModel,
          version:this.step3Component.packageModel,
          areas: [],
          computers:[],
        }
        let targets = Array();
        if(this.taskTargetModel == TaskTarget.Zone){
          for (let val of this.zoneComponent.selectionZone.selected.values()) {
            targets.push(val.area_id);
          }
          task['areas'] = targets;
        }
        if(this.taskTargetModel == TaskTarget.Computer){
          for (let val of this.computerComponent.datasource$.value) {
            targets.push( val.id );
          }
          task['computers'] = targets;
        }

        this.taskManager.checkParmas(task).then((res:any)=>{
          this.current ++;
          this.step4Component.pcCount = res.count?res.count:'未知';
          this.ref.markForCheck();    // 进行标注
          this.ref.detectChanges();   // 要多加一行这个 执行一次变化检测
        })
      }
    }else{
      this.current = this.current + 1
    }
  }
  checkWeekday(idx: number, value: any) {
    this.weekdays[idx] = value;
  }

  clickUpdate() {
    this.taskPeriodModel = this.taskPeriod.Now
    if(this.taskTypeModel == this.taskType.Client){
      this.steps = ClientAddSteps
    }else{
      this.steps = TaskAddSteps
    }
  }

  async submit() {
    let plannedTime = new Date(
      this.taskDateModel.year,
      this.taskDateModel.month - 1,
      this.taskDateModel.day,
      this.taskTime.hour,
      this.taskTime.minute,
      0,
    );

    let task = {
      type: this.taskTypeModel,
      period_type: this.taskPeriodModel,
      target: this.taskTargetModel,
      weekdays: this.weekdays,
      planned_at: plannedTime,
    };
    let content = new Map();
    //如果是客户端更新 加入三四步参数
    if(this.taskTypeModel == this.taskType.Client){
      content['arch'] = this.step3Component.architectureModel;
      content['version'] = this.step3Component.packageModel;
       //content{"arch":this.step3Component.architectureModel,"version":this.step3Component.packageModel}
      if(this.step4Component.formGroup.value.checkCycle){
        content['period'] = this.step4Component.formGroup.value.cycle
        content['start_time_at'] = this.step4Component.formGroup.value.startTime
        content['end_time_at'] = this.step4Component.formGroup.value.endTime
      }
      if(this.step4Component.formGroup.value.checkSpeed){
        content['download_speed'] = this.step4Component.formGroup.value.speed
      }
    }


    let targets = Array();
    console.log(this.taskTargetModel,TaskTarget.Zone,TaskTarget.Computer,TaskTarget.Personnel,TaskTarget.Software)
    switch (this.taskTargetModel) {
      case TaskTarget.Zone:
        for (let val of this.zoneComponent.selectionZone.selected.values()) {
          targets.push({ id: val.area_id });
        }
        task['areas'] = targets;
        break;
      case TaskTarget.Computer:
        console.log(this.computerComponent)
        for (let val of this.computerComponent.datasource$.value) {
          targets.push({ id: val.id });
        }
        task['computers'] = targets;
        break;
      case TaskTarget.Personnel:
        task['users'] = this.personnelComponent.selection.selected.map((p) => ({ id: p.id }));
        break;
      case TaskTarget.Software:
        content['softwares'] = this.softwareComponent.selection.selected.map((soft) => ({
          id: soft.id,
        }));
        break;
    }

    let createTask = async () => {
      task['content'] = content;
      await this.taskManager.create(task);
      this.router.navigate(['/task']);
    };

    if (this.taskPeriodModel == TaskPeriod.Schedule) {
      // 未选择周期日期
      if (!task.weekdays.some(v => v)) {
        this.toaster.warn('未设置执行周期');
        return false;
      }
    }

    if (this.taskTypeModel == TaskType.Script) {
      const scriptUrl: string = this.scriptForm.value['script']['content'];
      if (!scriptUrl.startsWith('blob:')) {
        this.toaster.warn('未上传脚本');
        return false;
      }
      if (scriptUrl.startsWith('blob:')) {
        const scriptBlob = await fetch(scriptUrl).then((resp) => resp.blob());

        var reader = new FileReader();
        reader.readAsText(scriptBlob, 'UTF-8');
        reader.onload = async (readerEvent) => {
          var fileContent = readerEvent.target['result'];
          content['script'] = fileContent;
          content['script_name'] = this.scriptForm.value['script']['name'];
          content['script_desc'] = this.scriptDesc;
          await createTask();
        };
      }
    } else {
      if (this.taskTypeModel == TaskType.Message) {
        content['title'] = '测试消息标题';
        content['message'] = '测试消息内容 测试消息内容 测试消息内容 测试消息内容';
      }
      await createTask();
    }
  }

  async clearScript() {
    this.scriptFileName = '';
    this.scriptFile = null;
  }

  async selectScript() {
    var input = document.createElement('input');
    input.type = 'file';

    var root = this;
    input.onchange = function (e?: any) {
      const target = event.target as HTMLInputElement;
      root.scriptFile = target.files[0];
      root.scriptFileName = root.scriptFile.name;
      root.ref.markForCheck();
    };
    input.click();
  }
}

const ClientAddSteps = [{ title: '设置任务基本属性' }, { title: '选择任务执行范围' },{title: '选择任务执行内容'},{title: '选择任务执行速度'}];
const TaskAddSteps = [{ title: '设置任务基本属性' }, { title: '选择任务执行范围' }];
